<?php

namespace App\Http\Controllers\Admin;

use App\Enums\CheckEnum;
use App\Enums\LoadCsvType;
use App\Enums\LoadScriptType;
use App\Enums\NoticeType;
use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\Game\Equip;
use App\Models\Game\EquipAttr;
use App\Models\Game\EquipNeedMonitor;
use App\Models\Game\GemList;
use App\Models\Game\Map;
use App\Models\Game\OperType;
use App\Models\Game\PetAttr;
use App\Models\Game\PetSkill;
use App\Models\Game\Server;
use App\Models\Game\SoulSkill;
use App\Models\Game\SoulTalent;
use App\Models\Game\UploadRecord;
use App\Utils\MyLog;
use App\Utils\ResponseUtil;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use League\Csv\Reader;
use Maatwebsite\Excel\Facades\Excel;

class HotExclPushController extends Controller
{
    private Request $request;

    /**
     * EnumController constructor.
     */
    public function __construct(Request $request)
    {
        $this->request = $request;

    }

    public function list(){
        $data = [
            'noticeType'=>NoticeType::map(),
            'map'=>Map::query()->select('id','name')->get(),
            'operType'=>OperType::query()->select('id','name')->get(),
            'equip'=>Equip::query()->select('id','name')->get(),
            'equip_monitor_ids'=>EquipNeedMonitor::query()->pluck('equip_id')->toArray(),
            'equipAttr'=>EquipAttr::query()->select('id','name')->get(),
            'gemList'=>GemList::query()->get(),
            'soulTalent'=>SoulTalent::query()->get(),
            'soulSkill'=>SoulSkill::query()->get(),
            'petAttr'=>PetAttr::query()->get(),
            'petSkill'=>PetSkill::query()->get(),
        ];
        return ResponseUtil::success($data);
    }

    public function import(){ //excel导入
        $data = $this->request->all();
        $name = data_get($data,'name');
        $table = data_get($data,'table');
        $file = $this->request->file('file');
        $sheets = Excel::toArray(null,$file);
        if($table=='any'){
            return $this->any($sheets[0]);
        }

        if ($file->getClientOriginalName() !== $name) {
            return ResponseUtil::error("请上传: " . $name);
        }
        if (!in_array($table,['ConstCfg','SkillBase','AuxiliarySkill','BufferBase','MonsterBase','CallMonster','Collection',
        'EquipBase' ,'EquipSyntAttr', 'EquipSynthesize', 'EquipInteMate','EquipInteAttr','ItemBase','TaskContent','EventTaskWeight','TaskBase', 'ItemDrop','DropData','RewardBase'
            ])) return ResponseUtil::error("非法操作");
        $res=$this->moveFile($file);
             if($res){

                 $admin = Auth::guard('admin')->user();
                 $admin = Admin::query()->find($admin->getAuthIdentifier());
                 $record['created_at'] = date("Y-m-d H:i:s");
                 $record['filename']=$name;
                 $record['username']=$admin->username;
                 UploadRecord::query()->insert($record);

             }
        return ResponseUtil::success();
    }


    public function push(){
        $data = $this->request->all();
        $excllist = data_get($data, 'excllist');
        $gameAreas = data_get($data, 'game_area');
        MyLog::info('提交的请求'.json_encode($data));
        MyLog::info('提交更新组'.json_encode($excllist));
        MyLog::info('哪些服务器'.json_encode($gameAreas));
        $uploadPath = public_path('uploads');
        foreach ($gameAreas as $gamearea){
            $txt = []; // 创建空的 $txt 数组
            foreach ($excllist as $key) {
            $ReLoadType = LoadScriptType::getParameter($key);
            $cValue = constant('App\Enums\LoadCsvType::' . $key);
            $fileNames = LoadCsvType::getFileNames($cValue);
            MyLog::info('KEY值'.json_encode($key));
            MyLog::info('枚举TYPE'.json_encode($ReLoadType));
            MyLog::info('文件名'.json_encode($fileNames));
            foreach ($fileNames as $filename){
                $Name = basename(str_replace('\\', '/', $filename));
                $filePath = $uploadPath . '/' . $Name;
                MyLog::info('文件地址'.json_encode($filePath));
                $content =\Illuminate\Support\Facades\File::get($filePath);
                $content = str_replace("\r\n", "\n", $content);
            // 根据需要处理文件内容
            $txt[]= [
                'file' => $filename,
                'txt' => $content,
            ];
            }
                $reload = [
                    "ReLoadType" => $ReLoadType, // emLoadScriptType枚举值
                    "list" => $txt, // 文件名以及文件内容 [{'file': name, 'txt': content}, ...]
                ];
                MyLog::info('获取文本内容' . json_encode($reload));
                $res=$this->send($reload, $gamearea);
                MyLog::info('推送返回结果' . json_encode($res));
                if(!$res){
                    throw new \Exception('同步失败');
                }
                sleep(1);
        }
        }
        return ResponseUtil::success();
    }

    public function check()
    {
        $data = $this->request->all();
        $excllist = data_get($data, 'excllist');
        $uploadPath = public_path('uploads');
        $success = true; // 校验是否成功的标志

        foreach ($excllist as $key) {
            $cValue = constant('App\Enums\LoadCsvType::' . $key);
            $fileNames = LoadCsvType::getFileNames($cValue);
            MyLog::info('KEY值' . json_encode($key));
            MyLog::info('文件名' . json_encode($fileNames));

            foreach ($fileNames as $filename) {
                $Name = basename(str_replace('\\', '/', $filename));
                MyLog::info('打开表的表头' . json_encode($Name));
                $fileonlyname = pathinfo($Name, PATHINFO_FILENAME);
                MyLog::info('获取文件名' . json_encode($fileonlyname));
                $filePath = $uploadPath . '/' . $Name;
                $csv = Reader::createFromPath($filePath, 'r');
                $csv1 = Reader::createFromPath($filePath, 'r');
                $csv->setHeaderOffset(0); // 设置表头的偏移量，默认为0
                $headers = $csv->getHeader();
                $headers = array_filter($headers, function ($header) {
                    return !empty($header); // 移除空字符串列
                });
                MyLog::info('打开表的表头' . json_encode($headers));
                $checkEums = CheckEnum::getParameter($fileonlyname);
                MyLog::info('配置数据' . json_encode($checkEums));

                $difference = array_diff($headers, $checkEums);
                MyLog::info('比较结果' . json_encode(count($difference)));

                if (!empty($difference)) {
                    // 校验失败，差异存在
                    return ResponseUtil::error($filename."表头差异存在", '-1');
                }
                MyLog::info('' . json_encode(count($difference)));

                $result = [];
                foreach ($csv1 as $row) {
                    $values = array_values($row); // 提取所有值
                    $firstValue = $values[0]; // 获取第一个值
                    $result[] = $firstValue;
                }
                MyLog::info('第一列数据' . json_encode($result));
                $isDuplicate = count($result) !== count(array_unique($result));
                MyLog::info('是否存在重复' . json_encode($isDuplicate));

                if ($isDuplicate) {
                    return ResponseUtil::error($filename."第一列存在重复值", '-1');

                }
            }
        }


            return ResponseUtil::success("校验通过");


    }

    private function send($requestBody=[], $gameArea=0){
        $row = Server::query()->where('can_push',1)->where("server_id",$gameArea)->first();
        $pushUrl = data_get($row,'push_url');
        $response = Http::withHeaders(['Content-Type'=>'application/json'])->post($pushUrl.'/Api/Config/ReLoadConfig',$requestBody);
        $body = json_decode($response->body(),true);
        $RetCode = data_get($body,'RetCode');
        MyLog::info('返回记录'.json_encode($RetCode));
        if ($RetCode===0) {
            return true;
        }
        else{
            return false;

        }
    }

    private function moveFile($file){
        try {
        $fileName = $file->getClientOriginalName();
        $uploadPath = public_path('uploads');
        $filePath = $uploadPath . '/' . $fileName;
        if (file_exists($filePath)) {
            unlink($filePath);
        }
        $file->move(public_path('uploads'), $fileName);
        } catch(\Exception $e){
            throw new \Exception('上传文档失败');
        }
        return true;
    }

}

